/**
 * 币安API服务模块
 * 处理币安交易所API请求
 */

const axios = require('axios');
const logger = require('../utils/logger');

class BinanceApiService {
  constructor() {
    this.baseURL = 'https://api.binance.com';
    this.retryCount = 3;
    this.retryDelay = 2000;
  }

  /**
   * 获取币安交易对列表
   * @returns {Promise<Array>} 交易对数组
   */
  async fetchTradingPairs() {
    for (let attempt = 1; attempt <= this.retryCount; attempt++) {
      try {
        logger.info(`正在获取币安交易对数据... (尝试 ${attempt}/${this.retryCount})`);
        
        const response = await axios.get(`${this.baseURL}/api/v3/exchangeInfo`, {
          timeout: 10000,
          headers: {
            'User-Agent': 'Binance-Monitor/3.0.0'
          }
        });

        if (!response.data || !response.data.symbols) {
          throw new Error('响应数据格式不正确');
        }

        // 只获取活跃的现货交易对，且过滤出包含USDT的交易对
        const allActivePairs = response.data.symbols
          .filter(symbol => 
            symbol.status === 'TRADING'
          )
          .map(symbol => symbol.symbol);
        
        // 只保留包含USDT的交易对
        const usdtPairs = allActivePairs.filter(symbol => symbol.includes('USDT'));

        logger.success(`成功获取 ${allActivePairs.length} 个币安交易对，过滤后保留 ${usdtPairs.length} 个USDT交易对`);
        return usdtPairs;

      } catch (error) {
        logger.error(`币安API请求失败 (尝试 ${attempt}/${this.retryCount}): ${error.message}`);
        
        if (attempt === this.retryCount) {
          throw new Error(`币安API请求最终失败: ${error.message}`);
        }
        
        // 等待后重试
        logger.info(`等待 ${this.retryDelay}ms 后重试...`);
        await new Promise(resolve => setTimeout(resolve, this.retryDelay));
      }
    }
  }

  /**
   * 获取特定交易对的详细信息
   * @param {string} symbol - 交易对符号
   * @returns {Promise<Object>} 交易对详细信息
   */
  async getSymbolInfo(symbol) {
    try {
      const response = await axios.get(`${this.baseURL}/api/v3/exchangeInfo`, {
        params: { symbol: symbol },
        timeout: 5000
      });

      if (!response.data || !response.data.symbols || response.data.symbols.length === 0) {
        throw new Error(`未找到交易对 ${symbol} 的信息`);
      }

      return response.data.symbols[0];
    } catch (error) {
      logger.error(`获取币安交易对 ${symbol} 详细信息失败: ${error.message}`);
      throw error;
    }
  }

  /**
   * 检查API连接状态
   * @returns {Promise<boolean>} 连接状态
   */
  async checkConnection() {
    try {
      logger.info('检查币安API连接状态...');
      
      const response = await axios.get(`${this.baseURL}/api/v3/ping`, {
        timeout: 5000
      });

      if (response.status === 200) {
        logger.success('币安API连接正常');
        return true;
      }
      
      return false;
    } catch (error) {
      logger.error(`币安API连接失败: ${error.message}`);
      return false;
    }
  }

  /**
   * 获取服务器时间（用于调试）
   * @returns {Promise<number>} 服务器时间戳
   */
  async getServerTime() {
    try {
      const response = await axios.get(`${this.baseURL}/api/v3/time`, {
        timeout: 5000
      });
      
      return response.data.serverTime;
    } catch (error) {
      logger.error(`获取币安服务器时间失败: ${error.message}`);
      throw error;
    }
  }

  /**
   * 解析交易对格式
   * 币安交易对格式: BTCUSDT -> BTC/USDT
   * @param {string} symbol - 币安交易对符号
   * @returns {string} 格式化的交易对名称
   */
  formatTradingPair(symbol) {
    // 常见的报价货币
    const quoteCurrencies = ['USDT', 'BUSD', 'BTC', 'ETH', 'BNB', 'USDC', 'TUSD', 'FDUSD'];
    
    for (const quote of quoteCurrencies) {
      if (symbol.endsWith(quote)) {
        const base = symbol.slice(0, -quote.length);
        return `${base}/${quote}`;
      }
    }
    
    // 如果没有匹配到常见报价货币，返回原始格式
    return symbol;
  }

  /**
   * 获取交易所基本信息
   * @returns {Object} 交易所信息
   */
  getExchangeInfo() {
    return {
      name: 'Binance',
      id: 'binance',
      website: 'https://www.binance.com',
      apiDocs: 'https://binance-docs.github.io/apidocs/spot/en/',
      rateLimits: {
        requests: 1200,
        perMinute: true
      }
    };
  }
}

module.exports = BinanceApiService;
